package se.webbzon.oschi01.gui;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class IconSheet<K> {
	
	private final BufferedImage iconSheet;
	private final Dimension d;
	private final Map<K,ImageIcon> iconMap;
	
	public IconSheet(URL url, Dimension d) throws IOException {
		InputStream is = url.openStream();
		iconSheet = ImageIO.read(is);
		is.close();
		this.d = d;
		iconMap = new HashMap<K,ImageIcon>();
	}
	
	public IconSheet(InputStream is, Dimension d) throws IOException {
		iconSheet = ImageIO.read(is);
		this.d = d;
		iconMap = new HashMap<K,ImageIcon>();
	}
	
	public boolean defineIcon(K key, int xOffset, int yOffset) {
		int x = d.width * xOffset;
		int y = d.height * yOffset;
		try {
			BufferedImage subImg = iconSheet.getSubimage(x, y, d.width, d.height);
			ImageIcon icon = new ImageIcon(subImg);
			iconMap.put(key,icon);
			return true;
		} catch (RasterFormatException e) {
			return false;
		}
	}
	
	public boolean undefineIcon(K key) {
		return iconMap.remove(key) != null;
	}
	
	public boolean isDefinedIcon(K key) {
		return iconMap.containsKey(key);
	}
	
	public ImageIcon getIcon(K key) {
		return iconMap.get(key);
	}

}
